package mark.tom.gear.base.interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.TimeUnit


/**
 * @Description: 网络请求记录拦截器
 * @Author: ttmk110@163.com
 * @Package: mark.tom.gear.base.interceptor
 * @Date: 2021/2/8
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date:
 * </ModifyLog>
 */
class RecordInterceptor : Interceptor {

    private var recorder: Recorder? = null

    constructor() {
        this.recorder = Recorder.DEFAULT
    }

    constructor(recorder: Recorder) {
        this.recorder = recorder
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val method: String = request.method
        val url: String = request.url.toString()
        val startNs = System.nanoTime()
        val response: Response = try {
            chain.proceed(request)
        } catch (e: IOException) {
            recorder?.record(method, url, true, -1)
            throw e
        }
        val tookMs: Long = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
        // 记录日志
        recorder?.record(method, url, false, tookMs)
        return response
    }

    interface Recorder {
        fun record(method: String?, url: String?, exception: Boolean, tookMs: Long)

        companion object {
            val DEFAULT: Recorder = object : Recorder {
                override fun record(method: String?, url: String?, exception: Boolean, tookMs: Long) {
                    // ignore
                }
            }
        }
    }
}